package com.btcode.web.freemarker.directive;

import freemarker.core.Environment;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 获取指定目录下的文件列表，用户前端自动引用资源 以_开头的文件不会被引用
 *
 * @author lrq 2016年10月25日
 */
public class FileListDirective implements TemplateDirectiveModel {


    private static String basePath;

    public static void setBasePath(String basePath) {
        FileListDirective.basePath = basePath;
    }

    public FileListDirective() {

    }

    @SuppressWarnings({"rawtypes", "deprecation"})
    @Override
    public void execute(Environment env, Map params, TemplateModel[] model,
        TemplateDirectiveBody body) throws TemplateException, IOException {

        String basePath = FileListDirective.basePath;
        String dir = params.get("dir") + "";

        basePath = prepartPath(basePath) + "/";
        basePath = prepartPath(basePath);
        dir = prepartPath(dir);

        String exceptFilesStr = params.get("exceptFiles") + "";
        List<String> exceptFileList = null;

        if (exceptFilesStr != null) {
            exceptFileList = new ArrayList<>();
            String[] exceptFiles = exceptFilesStr.split(",");
            for (int i = 0; i < exceptFiles.length; i++) {
                exceptFileList.add(exceptFiles[i]);
            }
        }

        List<String> filePaths = null;

        String fileDirPath = basePath + dir;
        fileDirPath = fileDirPath.replaceAll("\\\\", "/");
        filePaths = getFileList(new File(fileDirPath), basePath, exceptFileList);

        env.setVariable("fileList", ObjectWrapper.DEFAULT_WRAPPER.wrap(filePaths));

        body.render(env.getOut());
    }

    /**
     * 处理路径中的斜杠
     */
    private static String prepartPath(String path) {

        if (path == null) {
            return null;
        }

        if (!path.startsWith("/")) {
            path = "/" + path;
        }

        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }

        return path;
    }

    /**
     * gislin 2017年6月6日
     *
     * @param file 要处理的目录
     * @param baseRemovePath 基础目录
     * @param exceptFiles 要排除的文件
     */
    private static List<String> getFileList(File file, String baseRemovePath,
        List<String> exceptFiles) {
        List<String> result = new ArrayList<>();
        if (!file.isDirectory()) {
            if (file.getName().startsWith("_")) {
                return result;
            }

            String filePath = file.getPath();
            filePath = prepartPath(filePath);
            filePath = replaceBasePath(filePath, baseRemovePath);

            if (exceptFiles != null && exceptFiles.contains(filePath)) {
                @SuppressWarnings("unused") int o = 0;
            }
            else {
                result.add(filePath);
            }

        }
        else {
            File[] files = file.listFiles();
            if(files!=null){
                for (File fileItem : files) {
                    result.addAll(getFileList(fileItem, baseRemovePath, exceptFiles));
                }
            }
        }
        return result;
    }

    private static String replaceBasePath(String targetPath, String replacePath) {
        if (replacePath != null) {
            targetPath = targetPath.replaceAll("\\\\", "/");
            String result = targetPath.replaceAll(replacePath, "");
            return result;
        }
        return targetPath;
    }
}
